﻿using System;
using System.Data;
using System.Globalization;

namespace PublicDomain.Data.Csv.Metadata
{
    public static class CsvSchemaDataTable
    {
        public static DataTable GetSchemaTable(CsvDataFormat csvDataFormat)
        {
            if (csvDataFormat == null)
            {
                throw new ArgumentNullException("csvDataFormat");
            }

            var result = CreateSchemaTable();

            foreach (var columnsSchema in csvDataFormat.CsvColumnsDefinitions)
            {
                var row = result.NewRow();

                row["ColumnName"] = columnsSchema.ColumnName;
                row["ColumnOrdinal"] = columnsSchema.ColumnOrdinal;
                row["DataType"] = columnsSchema.DataType;
                row["ColumnSize"] = columnsSchema.ColumnSize;

                result.Rows.Add(row);
            }

            return result;
        }

        private static DataTable CreateSchemaTable()
        {
            var result = new DataTable("SchemaTable");
            result.Locale = CultureInfo.InvariantCulture;

            result.Columns.Add(new DataColumn { ColumnName = "ColumnName", DataType = typeof(string), AllowDBNull = false });
            result.Columns.Add(new DataColumn { ColumnName = "ColumnOrdinal", DataType = typeof(int), AllowDBNull = false });
            result.Columns.Add(new DataColumn { ColumnName = "DataType", DataType = typeof(DbType), AllowDBNull = false });
            result.Columns.Add(new DataColumn { ColumnName = "ColumnSize", DataType = typeof(int), AllowDBNull = false });

            return result;
        }
    }
}
